#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 65536
#define MAX_PACKET_SIZE 65535

// 打印 IP 地址
void print_ip_address(struct in_addr addr) {
    char ip_str[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &addr, ip_str, INET_ADDRSTRLEN);
    printf("%s", ip_str);
}

// 处理捕获到的数据包
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
    struct ip *ip_header;
    struct icmphdr *icmp_header;
    int ip_header_length;

    // 跳过以太网帧头
    ip_header = (struct ip *)(pkt_data + 14);
    ip_header_length = ip_header->ip_hl * 4;

    // 检查是否为 ICMP 协议
    if (ip_header->ip_p == IPPROTO_ICMP) {
        icmp_header = (struct icmphdr *)(pkt_data + 14 + ip_header_length);

        // 检查是否为 ICMP ECHO 请求
        if (icmp_header->type == ICMP_ECHO) {
            printf("--------------------- ICMP ECHO Request Packet ---------------------\n");
            printf("Source IP: ");
            print_ip_address(ip_header->ip_src);
            printf("\n");
            printf("Destination IP: ");
            print_ip_address(ip_header->ip_dst);
            printf("\n");
            printf("ICMP Type: %d (ECHO Request)\n", icmp_header->type);
            printf("ICMP Code: %d\n", icmp_header->code);
            printf("ICMP Checksum: 0x%04x\n", ntohs(icmp_header->checksum));
            printf("ICMP Identifier: 0x%04x\n", ntohs(icmp_header->un.echo.id));
            printf("ICMP Sequence Number: 0x%04x\n", ntohs(icmp_header->un.echo.sequence));
            printf("--------------------------------------------------------------\n");
        }
    }
}

int main(int argc, char *argv[]) {
    pcap_t *handle;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct bpf_program fp;
    char filter_exp[] = "icmp and icmp[0] == 8";  // 过滤 ICMP ECHO 请求
    bpf_u_int32 net;

    // 检查命令行参数
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <interface>\n", argv[0]);
        return 1;
    }

    // 打开网络接口进行数据包捕获
    handle = pcap_open_live(argv[1], MAX_PACKET_SIZE, 1, 1000, errbuf);
    if (handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", argv[1], errbuf);
        return 2;
    }

    // 编译过滤规则
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
        return 3;
    }

    // 应用过滤规则
    if (pcap_setfilter(handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
        return 4;
    }

    // 开始捕获数据包
    pcap_loop(handle, 0, packet_handler, NULL);

    // 关闭捕获句柄
    pcap_close(handle);
    return 0;
}